// 点击提交模块
const form = document.querySelector('form')
const agree = document.querySelector('[name=agree]')
const items = form.querySelectorAll('[name]')
    // 取出本地存储的数据 转换为对象
const data = localStorage.getItem('user_data')
const arr = data ? JSON.parse(data) : [];
// 用户名验证
const exist = document.querySelector('.exist')
items[0].addEventListener('change', function(e) {
    const nameArr = []
    exist.innerHTML = ''
    console.log(arr.length);
    if (arr.length > 0) {
        for (let item of arr) {
            // console.log(item);
            nameArr.push(item.username)
        }
        if (!nameArr.includes(items[0].value)) {
            exist.innerHTML = '用户名不存在'
            console.log(nameArr);
            return e.preventDefault()
        }
    }
})

// 密码验证
const msg = document.querySelector('.msg')
items[1].addEventListener('change', function(e) {
        const pwdArr = []
        msg.innerHTML = ''
        if (arr.length > 0) {
            for (let item of arr) {
                pwdArr.push(item.password)
            }
            if (!pwdArr.includes(items[1].value)) {
                msg.innerHTML = '密码错误'
                console.log(pwdArr);
                return e.preventDefault()
            }
        }
    })
    // 表单提交
const agreeMsg = document.querySelector('.agree_msg')

// const singleArr = []
form.addEventListener('submit', function(e) {
    agreeMsg.innerHTML = ''
    e.preventDefault()
    if (!agree.checked) {
        agreeMsg.innerHTML = '请勾选同意协议'
        return
    }
    if (msg.innerHTML === '密码错误' || exist.innerHTML === '用户名不存在') {
        return
    }
    if (items[0].value === '' || items[1].value === '') {
        return
    }
    //    存入、更新数据
    const date = new Date();
    const month = date.getMonth() + 1
    const day = date.getDate()
        // 存入正在登录的用户名  判断用户
    localStorage.setItem('nowLogin', JSON.stringify(items[0].value))

    const data1 = localStorage.getItem(`${items[0].value}+${month}+${day}`)
    const arrToday = data1 ? JSON.parse(data1) : [];

    const data2 = localStorage.getItem(`${items[0].value}+${month}+${day+1}`)
    const arrTom = data2 ? JSON.parse(data2) : [];
    console.log(arrTom);
    // singleArr.push(singleObj)
    localStorage.setItem(`${items[0].value}+${month}+${day}`, JSON.stringify(arrToday))
    localStorage.setItem(`${items[0].value}+${month}+${day+1}`, JSON.stringify(arrTom))
    location.href = './planning.html'
})

// 注册
const sign = document.querySelector('.sign')
sign.addEventListener('click', function() {
    location.href = './register.html'
})